﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;

namespace NORM.Common
{
    public class Network
    {
        /// <summary>
        /// DateTime时间格式转换为Unix时间戳格式
        /// </summary>
        /// <param name="Datetime">时间</param>
        /// <param name="Milliseconds">是否保留毫秒</param>
        /// <returns></returns>
        public static string ConvertTimestamp(DateTime Datetime, bool Milliseconds = false)
        {
            string result = string.Empty;
            System.DateTime Starttime =
                TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            if (!Milliseconds)
                result = ((long)(Datetime - Starttime).TotalSeconds).ToString();
            else
                result = ((long)(Datetime - Starttime).TotalMilliseconds).ToString();
            return result;
        }

        /// <summary>
        /// Unix时间戳转为C#格式时间 
        /// </summary>
        /// <param name="Timestamp">Unix时间戳</param>
        /// <param name="Milliseconds">是否包含毫秒</param>
        /// <returns></returns>
        public static DateTime ConvertDatetime(long Timestamp, bool Milliseconds = false)
        {
            DateTime Starttime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            long lTime = 0;
            if (Milliseconds)
            {                 
                lTime = long.Parse(Timestamp / 1000 + "" + Timestamp % 1000 + "0000"); 
            }
            else
            {
                lTime = long.Parse(Timestamp + "0000000"); 
            }
            TimeSpan Nowtime = new TimeSpan(lTime);                     
            return Starttime.Add(Nowtime);
        }

        /// <summary>
        /// 模拟HTTP POST/GET 
        /// </summary>
        /// <param name="url">url地址</param>
        /// <param name="type">POST/GET</param>
        /// <param name="data">数据</param>
        /// <param name="encode">编码格式 默认UTF-8</param>
        /// <param name="state">状态信息</param>
        /// <returns>返回信息</returns>
        public static string Http(string url, string type, string data, Encoding encode, out string state)
        {
            string context = string.Empty;

            state = string.Empty;

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.ProtocolVersion = HttpVersion.Version10;  
            request.ContentType = "application/x-www-form-urlencoded";
            request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";  

            try
            {
                if (!string.IsNullOrEmpty(data))
                {
                    request.ContentLength = encode.GetByteCount(data);
                    using (Stream requestStream = request.GetRequestStream())
                    {
                        using (StreamWriter streamWriter = new StreamWriter(requestStream, encode))
                        {
                            streamWriter.Write(data);
                        }
                    }
                }

                if (url.StartsWith("https",StringComparison.OrdinalIgnoreCase))
                {
                    ServicePointManager.ServerCertificateValidationCallback = 
                        new RemoteCertificateValidationCallback((object sender, X509Certificate certificate, X509Chain chain, System.Net.Security.SslPolicyErrors errors) => { 
                            return true; //始终接受
                        });
                    ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;// SecurityProtocolType.Tls1.2;
                }

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                using (Stream responseStream = response.GetResponseStream())
                {
                    using (StreamReader streamReader = new StreamReader(responseStream, encode))
                    {
                        context = streamReader.ReadToEnd();                         
                    }
                }

                state = "SUCCESS";

            }
            catch (Exception ex)
            {
                state = "FAIL";
                context = ex.Message;               
            }

            request.Abort();

            return context;

        }

        /// <summary>
        ///  CRC-16 CCITT (Kermit)算法
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static ushort CRC16(byte[] data)
        {
            return CRC.CRC16_CCITT_XModem(data);
        }

        /// <summary>
        /// CRC-32-IEEE 802.3查表法 
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static uint CRC32(byte[] data)
        {
            return CRC.CRC32(data);
        }

    }    
}
